package org.elzat.healthboxgatewayapp.config;

import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.elzat.healthboxgatewayapp.credentials.HealthBoxAuthority;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpMethod;

import java.util.ArrayList;
import java.util.List;

@Data
@ToString
@ConfigurationProperties(prefix = "health-box.security")
@RefreshScope
public class HealthBoxSecurityConfig {

    private List<String> permitAll;
    private List<SecurityFilter> filters;

    public List<ValidSecurityFilter> resolveFilters() {
        List<ValidSecurityFilter> validFilters = new ArrayList<>();
        for (SecurityFilter filter : filters) {
            ValidSecurityFilter valid = filter.resolve();
            if (valid == null) continue;
            validFilters.add(valid);
        }
        return validFilters;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private static class SecurityFilter {
        private String method;
        private String path;
        private String authority;
        ValidSecurityFilter resolve() {
            HttpMethod m = HttpMethod.resolve(method);
            if (m == null) return null;
            HealthBoxAuthority auth;
            try {
                auth = HealthBoxAuthority.valueOf(authority);
            } catch (IllegalArgumentException ex) {
                return null;
            }
            return ValidSecurityFilter.builder()
                    .method(m).path(path)
                    .authority(auth).build();
        }
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    public static class ValidSecurityFilter {
        private HttpMethod method;
        private String path;
        private HealthBoxAuthority authority;
    }
}
